package a12_图论;

import java.util.Scanner;

/**
 * <p>
 * a09_沉没孤岛复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/4/15
 */
public class a09_沉没孤岛复习1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int rows = scanner.nextInt();
        int cols = scanner.nextInt();
        int[][] grid = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                grid[i][j] = scanner.nextInt();
            }
        }

        //标记所有边上的岛屿
        boolean[][] visited = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(i == 0 || i == rows-1 || j == 0 || j == cols-1){
                    if(grid[i][j] == 1 && !visited[i][j]){
                        visited[i][j] = true;
                        dfs(grid,visited,i,j);
                    }
                }
            }
        }

        //让所有没有访问的土地变成海洋
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(grid[i][j] == 1 && !visited[i][j]){
                    grid[i][j] = 0;
                }
            }
        }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(grid[i][j]);
                if(j != cols - 1){
                    System.out.print(" ");
                }
            }
            System.out.println();
        }


    }

    public static final int[][] dirs = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
    private static void dfs(int[][] grid,boolean[][] visited, int x, int y) {
        for (int[] dir : dirs) {
            int nextX = x + dir[0];
            int nextY = y + dir[1];
            if(nextX >= 0 && nextX < grid.length && nextY >= 0 && nextY < grid[0].length){
                if(grid[nextX][nextY] == 1 && !visited[nextX][nextY]){
                    visited[nextX][nextY] = true;
                    dfs(grid, visited, nextX, nextY);
                }
            }
        }
    }
}
